package com.view;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;

import com.control.BufferControl;
import com.control.CommandControl;
import com.control.RightPanelControl;
import com.control.TreeItemControl;
import com.model.Buffer;
import com.view.optionpanel.ShowMessage;

public class MainFrame extends JFrame implements ActionListener, Observer, MouseListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JSplitPane splitPanel, area;
	protected JTextArea path, search;
	public JMenuItem item1, item7,item2, item3, oneItem, twoItem, threeItem, item4, item5, item6;
	private TreeItemControl tree;
	public JButton icon;
	public JPanel js, jtree, right;
	public JPanel main;
	private String paths;
	private int width, height;

	public MainFrame() {
		this.setTitle("磁盘文件模拟系统");
		this.width = 800;
		this.height = 600;
		this.setSize(width, height);
		this.setLocation(310, 60);
		paths = "磁盘目录";// 初始目录
		main = new JPanel(new BorderLayout());// 设置主界面布局
		main.add(getTitlePanel(), BorderLayout.NORTH);
		main.add(getSplitPanel(), BorderLayout.CENTER);
		main.add(new JLabel("版权所有：施红宇", JLabel.CENTER), BorderLayout.SOUTH);
		this.add(main);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	private JSplitPane getSplitPanel() {// 中心界面代码
		if (splitPanel == null) {
			splitPanel = new JSplitPane();
		}
		splitPanel.setOneTouchExpandable(true);// 支持左右两边界面隐藏
		JScrollPane leftPane = new JScrollPane(getLeftPanel());// 获取左边部分目录树
		splitPanel.add(leftPane, JSplitPane.LEFT);
		// 获取右边面板，并设置滚动条
		JScrollPane rightPane = new JScrollPane(getRightPanel(paths), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		splitPanel.add(rightPane, JSplitPane.RIGHT);
		splitPanel.setDividerLocation(150);
		splitPanel.setContinuousLayout(true);
		// splitPanel.setEnabled(false);//设置分割栏是否可以划分
		return splitPanel;
	}

	private JPanel getLeftPanel() {
		jtree = new JPanel();
		jtree.setLayout(new BorderLayout());
		this.tree = new TreeItemControl();// 调用control方法
		this.tree.addObserver(this);// 设置主界面可以观察control的变化
		jtree.add(this.tree.TreePanel(), BorderLayout.WEST);// 获取目录
		return this.jtree;
	}

	private JPanel getRightPanel(String path) {
		RightPanelControl rControl = new RightPanelControl(path);
		right = rControl.getRightPanel();
		rControl.addObserver(this);// 设置主界面可以观察右部分的变化
		right.addMouseListener(this);// 添加鼠标事件
		return right;
	}

	public JPopupMenu getJPopupMenu() {// 鼠标右键目录
		JPopupMenu tanchu = new JPopupMenu();
		oneItem = new JMenuItem("新建文件夹");
		oneItem.addActionListener(this);
		twoItem = new JMenuItem("新建文件");
		twoItem.addActionListener(this);
		threeItem = new JMenuItem("删除当前目录");
		threeItem.addActionListener(this);
		tanchu.add(oneItem);
		tanchu.add(twoItem);
		tanchu.add(threeItem);
		return tanchu;
	}

	public JMenuBar getJMenuBar() {// 工具栏目录
		JMenuBar jMenuBar = new JMenuBar();
		JMenu menu = new JMenu("功能");
		JMenu menuB = new JMenu("操作");
		jMenuBar.add(menu);
		jMenuBar.add(menuB);
		item1 = new JMenuItem("新建文件夹");
		item1.addActionListener(this);
		item2 = new JMenuItem("删除当前目录");
		item2.addActionListener(this);
		item3 = new JMenuItem("新建文件");
		item3.addActionListener(this);
		item6 = new JMenuItem("文件分配表FAT");
		item6.addActionListener(this);
		item7 = new JMenuItem("已打开文件表");
		item7.addActionListener(this);
		item4 = new JMenuItem("命令行");
		item4.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_MASK));
		item4.addActionListener(this);
		item5 = new JMenuItem("命令行帮助");
		item5.addActionListener(this);
		item1.setAccelerator(KeyStroke.getKeyStroke('F', InputEvent.CTRL_MASK));
		item3.setAccelerator(KeyStroke.getKeyStroke('B', InputEvent.CTRL_MASK));
		item2.setAccelerator(KeyStroke.getKeyStroke('G', InputEvent.CTRL_MASK));
		item6.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_MASK));
		item7.setAccelerator(KeyStroke.getKeyStroke('E', InputEvent.CTRL_MASK));
		menu.add(item1);
		menu.add(item3);
		menu.add(item2);
		menu.add(item6);
		menuB.add(item4);
		menuB.add(item5);
		menu.add(item7);
		return jMenuBar;
	}

	private JPanel getTitlePanel() {// 顶部路径框和搜索框的布局
		JPanel title = new JPanel();
		JPanel head = new JPanel();
		title.setLayout(new BorderLayout());
		head.setLayout(new BorderLayout());
		head.add(new JPanel(), BorderLayout.NORTH);
		head.add(getPathTextAtea(), BorderLayout.SOUTH);
		title.add(head, BorderLayout.NORTH);
		title.add(getJMenuBar(), BorderLayout.SOUTH);
		return title;
	}

	private JSplitPane getPathTextAtea() {// 获取搜索框和目录框
		if (area == null) {
			search = new JTextArea();
			path = new JTextArea();
			path.setText(paths);
			path.setEditable(false);
			area = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, path, null);
		}
		area.setDividerLocation(550);
		return area;
	}

	@Override
	public void actionPerformed(ActionEvent e) {// 鼠标点击事件
		if (e.getActionCommand().equals("新建文件夹")) {
			String name = JOptionPane.showInputDialog(null, "请输入文件夹名", "新建", JOptionPane.INFORMATION_MESSAGE);
			if (!name .equals("")) {

				int a[] = new int[128];
				FileReader fr = null;
				try {
					fr = new FileReader("resources/test2.txt");
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				BufferedReader br = new BufferedReader(fr);
				String line = "";
				int i = 0;
				try {
					while ((line = br.readLine()) != null) {
						int d = Integer.parseInt(line);
						a[i] = d;
						a[0] = -1;
						i++;
						// System.out.println(d);
					}
				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					br.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					fr.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				int j = 1;
				for (; j < 128; j++) {
					if (a[j] == 0) {
						break;
					}
				}
				if (j != 128) {
					this.tree.AddTreeFolder(paths, name);
					a[j] = -1;
					this.tree.setStartNum(this.paths + "\\" + name, j);
				} else {
					ShowMessage.warning("存储空间已满！", null);
				}
				File q = new File("resources/test2.txt");
				Writer rdf = null;
				try {
					rdf = new FileWriter(q);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// rdf.write("-1\n");
				try {
					rdf.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				FileWriter fileWriter = null;
				try {
					fileWriter = new FileWriter("resources/test2.txt", true);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				for (int f = 0; f < a.length; f++) {
					try {
						fileWriter.write(String.valueOf(a[f]) + "\n");
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				try {
					fileWriter.flush();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					fileWriter.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				getSplitPanel();
				validate();
			}
			else {
				ShowMessage.error("文件夹名不得为空！", null);
			}
		} else if (e.getActionCommand().equals("删除当前目录")) {
			this.tree.DeleteTree(this.paths);
			String newPathString = "";
			String[] temp = paths.split("\\\\");
			for (int i = 0; i < temp.length - 1; i++) {
				newPathString = newPathString + temp[i] + "\\";
			}
			newPathString = newPathString.substring(0, newPathString.length() - 1);
			this.paths = newPathString;
			this.path.setText(newPathString);
			getSplitPanel();
			validate();
		} else if (e.getActionCommand().equals("新建文件")) {	
			NewFileDialog newFile = new NewFileDialog();
			int p=newFile.get_i();
			if(p==1){
			String fileName = newFile.getFileName();
			String fileType = newFile.getFileType();
			int b = 0;
			if (!fileName.equals("")&& !fileType.equals("选择文件类别")) {
				if (this.tree.AddTreeFile(paths, fileName + fileType)) {
					int i = this.tree.ItemTree.getIdByPath(paths + "\\" + fileName + fileType);
					NewFile a = new NewFile(fileName + fileType, i);
					
					b = a.getStart();
					this.tree.setStartNum(this.paths + "\\" + fileName + fileType, b);

					getSplitPanel();
					validate();
				}
			} else {
				ShowMessage.error("文件名或文件类型不得为空！", null);
			}
			if (b == -128) {
				this.tree.DeleteTree(this.paths + "\\" + fileName + fileType);
				getSplitPanel();
				validate();
			}
			}
		} else if (e.getActionCommand().equals("文件分配表FAT")) {
			new Fat();
		} 
		else if (e.getActionCommand().equals("已打开文件表")) {
			new BufferList();
		}
		else if (e.getSource() == item5) {
			Toolkit tk = Toolkit.getDefaultToolkit();
			new HelpDialog((tk.getScreenSize().width - this.width / 2) / 2,
					(tk.getScreenSize().height - this.height / 2) / 2);
		} else if (e.getSource() == item4) {
			CommandControl cmd = new CommandControl();
			String name = JOptionPane.showInputDialog(null, "请输入操作命令", "命令窗口", JOptionPane.INFORMATION_MESSAGE);
			if (name != null) {
				String[] cms = name.split(" ");
				switch (cms[0]) {
				case "cd":
					String cdPath = cmd.cdCommand(this.paths, name);
					if (tree.CheckFloder(cdPath)) {
						this.paths = cdPath;
						this.path.setText(this.paths);
						getSplitPanel();
						validate();
					}else{
						ShowMessage.error("不能切换到文件!", null);
					}
					break;
				case "rm":
					String rmPath = cmd.rmCommand(this.paths, name);
					List<Buffer> buffers=BufferControl.getInstance().getBuffers();
					int k=buffers.size();
					int j=0;
					for(;j<k;j++){
						Buffer y=buffers.get(j);
						if(y.getPath().equals(rmPath)){
							j=-1;
								ShowMessage.error("该文件已打开，请在已打开文件表中关闭再删除！", null);
								break;
							
						}
					}
					if(j!=-1){
					if(tree.ExitPath(rmPath)){
					this.tree.DeleteTree(rmPath);
					this.paths = rmPath;
					String newPathString = "";
					String[] temp = paths.split("\\\\");
					for (int i = 0; i < temp.length - 1; i++) {
						newPathString = newPathString + temp[i] + "\\";
					}
					newPathString = newPathString.substring(0, newPathString.length() - 1);
					this.paths = newPathString;
					this.path.setText(newPathString);
					getSplitPanel();
					validate();
					}
					}
					break;
				default:
					ShowMessage.error("错误命令符", null);
					break;
				}

			}

		}

	}

	@Override
	public void update(Observable o, Object arg) {// 观察到被观测目标发生变化
		if (arg.toString().split("\\\\")[0].equals("删除文件")) {// 鼠标右键删除文件的方法
			this.paths = this.paths + "\\" + arg.toString().split("\\\\")[1];
			this.tree.DeleteTree(this.paths);
			String newPathString = "";
			String[] temp = paths.split("\\\\");
			for (int i = 0; i < temp.length - 1; i++) {
				newPathString = newPathString + temp[i] + "\\";
			}
			newPathString = newPathString.substring(0, newPathString.length() - 1);
			this.paths = newPathString;
			this.path.setText(newPathString);
			getSplitPanel();
			validate();

		} else {
			// System.out.println("panduanwenjianjia"+arg.toString());
			// System.out.println(tree.CheckFloder(arg.toString()));
			if (tree.CheckFloder(arg.toString())) {// 判断是否为文件夹，是即可进入下一个目录
				this.path.setText(arg.toString());
				this.paths = arg.toString();
				getSplitPanel();
				validate();
			} else {
				this.path.setText(arg.toString());
				this.paths = arg.toString();
			}
		}
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		int c = e.getButton();
		if (c == MouseEvent.BUTTON3) {
			getJPopupMenu().show(this.right, e.getX(), e.getY());
		}

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {

	}

	@Override
	public void mouseExited(MouseEvent arg0) {

	}

	@Override
	public void mousePressed(MouseEvent arg0) {

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {

	}

}
